<template>
   <view class="wrap">
        <view class="forumDetails">
            <view class="type">
                <view style="display: flex; align-items: center;width: 300rpx;">
                    <image class="typeImg" src="../../../static/type.svg" mode="aspectFill" lazy-load="false" @error="" @load=""></image>
                    <view class="typeText">帖子类型</view>
                </view>
                <uni-combox placeholder="请选择帖子类型"  :border="false" :candidates="forumType" v-model="forumVls"></uni-combox>
            </view>
            <view class="line"></view>
            <!-- <input class="inputSyl" type="text" placeholder="请输入标题" placeholder-style="font-size: 14px; color: #D1D1D1;" v-model="title"> -->
            <!-- <view class="line"></view> -->
            <textarea maxlength="-1" v-model="content" placeholder="请输入帖子内容" placeholder-style="font-size: 14px; color: #D1D1D1;" class="contentSyl"></textarea>
            <view class="imgWrap">
                <uni-file-picker fileMediatype="image"  limit="9" title="最多选择9张图片" @select="select" @delete='deleteimg'></uni-file-picker>
            </view>
         <!--   <view style="display: flex;margin-top: 20rpx;">
                <image style="width: 214rpx;height: 214rpx;" v-if="isEditor" v-for="(item,idx) in imageValue" :key="idx" :src="item" />
                
            </view> -->
        </view>
        <view class="forumWrap" >
            <!-- <view class="draft" @click="addForum('draft')">存草稿</view> -->
            <view class="forumBtn" @click="addForum('publish')">确定发布</view>
        </view>
        <!-- 提示信息弹窗 -->
        <uni-popup ref="message" type="message">
            <uni-popup-message :type="msgType" :message="messageText" :duration="2000"></uni-popup-message>
        </uni-popup>
   </view>
</template>
<script>
import { addForumAPI, notebookAPI, editorForumAPI, checkImgAPI } from '../../../utils/api'
import { baseURL } from '../../../utils/baseUrl';
export default {
   data() {
     return {
        id:'',
		flag: true,
        content:'',
        forumVls:'',
        msgType: '',
		messageText: '',
        imageValue:[],
        forumType:[],
		status:'',
        isEditor:false
     }
   },
   onLoad(value){
    console.log(value,'value');
	this.forumVls = value.wstype == '全部' ? '健康' : value.wstype
    this.status = value.status
   
    if(value?.info != undefined){
        this.isEditor = true
        const info = JSON.parse(value?.info)
        this.forumVls = info.postType
        this.content = info.postContent
        const img = info.headPortrait
        this.imageValue.push(img)
        this.id = info.id
    }
    this.getTbar();
   },   
   methods: {
    async getTbar(){
        try {
            const res = await notebookAPI();
            const arr = []
            for(const vls of res.result.manualValues){
                arr.push(vls.itemText)
            }      
            console.log('arr==========>',arr)      
            this.forumType = arr
        } catch (error) {

        } 
    },
	//删除图片
	deleteimg(e){
		const font = e.tempFilePath.lastIndexOf('/') + 1
		const second = e.tempFilePath.lastIndexOf('.')
		const path = e.tempFilePath.slice(font,second)
		let arr = []
		this.imageValue.map((item)=>{
		const leftindex = 	item.lastIndexOf('/') + 1
		const rightindex =	item.lastIndexOf('_')
		const result =	item.slice(leftindex,rightindex)
		arr.push(result)
		})
		const index =	arr.findIndex(v => v === path);
		this.imageValue.splice(index,1)
	},
    // 获取上传状态
    select(e){
        console.log('选择文件：',e)
        let arr = []
        uni.showLoading({
            title: '上传中...'
        });
        const tempFilePaths = e.tempFilePaths;
        for(let i=0; i<tempFilePaths.length; i++ ){
            uni.uploadFile({
                url: `${baseURL}/sys/common/upload`, //仅为示例，非真实的接口地址
                filePath: tempFilePaths[i],
                name: 'file',
                formData: {
                    'biz': 'postPicture'
                },
                header:{
                    "X-Access-Token": uni.getStorageSync("token")
                },
                success: async (uploadFileRes) => {
                    const imgInfo =  JSON.parse(uploadFileRes.data);
                    arr.push({
                        order:i,
                        src:imgInfo.message
                    })
					// await checkImgAPI(imgInfo.message,"帖子")
					if(arr.length == tempFilePaths.length){
                        uni.hideLoading();
                        console.log("排序之前",arr)
                        let newOrderArr = arr.sort((a, b) => a.order - b.order); 
                        console.log("排序以后",newOrderArr);
                        for(let i in newOrderArr){
                            this.imageValue.push(newOrderArr[i].src)
                        }
                        // this.imageValue = newOrderArr
                        // let orderArr = _.sortBy(arr,['order']);
                        // console.log("orderArr",orderArr)
                    }
                }
            });
        }

        
        // this.imageValue.push(imgInfo.message)
        
    },
    // 发帖
    async addForum(type){
        // console.log('数据======>',this.title, this.content)
		 if(this.flag){
			 this.flag = false
			 let _this = this
			 setTimeout(() => {
				 _this.flag = true
			 },5000)
			 try {
			 	if(this.content == ''){
			 		this.msgType = 'error'
			 	    this.messageText = "请填写内容"
			 		  this.$refs.message.open()
			 	}else
			 	{
			 		const params = {
			 		    postInformation:{
			 		        // title: this.title,
			 		        postContent: this.content,
			 		        postType: this.forumVls,
			 		        postState: type == 'draft'?'1':'0'
			 		    },
			 		    pictureLink: `${baseURL}/`,
			 		    picturePaths: this.imageValue
			 		
			 		}
			 		if(this.isEditor){
			 		    const res = await editorForumAPI(this.id)
			 		    console.log('res=============>',res)
			 		    if(res.code == 200){
			 		        
			 				uni.showToast({
			 					title:'发布成功'
			 				})
			 		        setTimeout(() => {
			 		            uni.navigateBack({
			 		                delta:1,
			 		            })
			 		        }, 1000);
			 		    }
			 		}else{
			 		    const res = await addForumAPI(params)
			 		    if(res.code == 200){
			 				uni.showToast({
			 					title:'发布成功'
			 				})
			 		        if(this.status == 5)
			 		        {
			 		            uni.navigateTo({
			 		                url:'../../../subPackagesB/pages/reward/reward'
			 		            })
			 		        }else
			 		        {
			 		            setTimeout(() => {
			 		                uni.navigateBack({
			 		                    delta:1,
			 		                })
			 		            }, 1000);
			 		        }
			 		    
			 		    }else{
			 		        // this.msgType = 'error'
			 		        // this.messageText = res.message
			 		        // this.$refs.message.open()
			 		    }
			 		}
			 	}
			    
			     
			     
			 } catch (error) {
			     
			 }
		 }
        

     },
   }
};
</script>
<style lang='scss' scoped>
.type{
    display: flex;
    align-items: center;
    justify-content: space-between;
    .typeImg{
        width: 36rpx;
        height: 36rpx;
        margin-right: 10rpx;
    }
}
.imgWrap{
    margin-top: 30rpx;
}
.inputSyl{
    padding: 20rpx 0;
}
.contentSyl{
    padding: 20rpx 0;
}
.line{
    width: 100%;
    height: 2rpx;
    background-color: #F5F5F5;
}
.forumDetails{
    margin: 30rpx;
    // margin-bottom: 200px;
    // padding-bottom: 200px;
}
.wrap{
    width: 100%;
}
.forumWrap{
    width: 100%;
    display: flex;
    justify-content: space-between;
    // position: absolute;
    // bottom: 30rpx;
    .draft{
        margin-left: 30rpx;
        width: 224rpx;
        height: 84rpx;
        line-height: 84rpx;
        text-align: center;
        border-radius: 8rpx 8rpx 8rpx 8rpx;
        opacity: 1;
        border: 2rpx solid #FF7F22;
        color: #FF7F22;

    }
    .forumBtn{
        margin: 30rpx;
        width: 100%;
        height: 88rpx;
        line-height: 88rpx;
        text-align: center;
        color: #fff;
        background: #FF7F22;
        border-radius: 8rpx 8rpx 8rpx 8rpx;
        opacity: 1;
    }
}
</style>